<?php
/**
 * File: Address.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/19 16:36
 */

namespace Common\Service;
class Attachment extends Base
{
    /**
     * 生成序列号（不唯一）
     * @return mixed
     */
    protected function getSerial()
    {
        $serial = generate_unique_serial('FJ');
        $instance = M('attachment')->where(['serial' => $serial])->find();
        if ($instance) {
            $serial = $this->getSerial();
        }
        return $serial;
    }

    /**
     * 存储附件数据
     * @param $files
     * @return bool|mixed
     */
    public function saveAttachment($files)
    {
        if (empty($files)) {
            return false;
        }
        $serial = $this->getSerial();
        $userId = user()->id;
        foreach ($files as $file) {
            $data['serial'] = $serial;
            $data['user_id'] = $userId;
            $data['path'] = '/' . UPLOAD_PATH . $file['savepath'] . $file['savename'];
            $data['name'] = $file['name'];
            $data['ext'] = $file['ext'];
            $data['size'] = $file['size'];
            $data['hash'] = $file['sha1'];
            $res = M('attachment')->add($data);
        }
        if (empty($res)) {
            return false;
        }
        return $serial;

    }

    /**
     * 存储url附件数据
     * @param $urls
     * @return bool|mixed
     */
    public function saveUrlAttachment($urls)
    {
        if (empty($urls)) {
            return false;
        }
        $serial = $this->getSerial();
        $userId = user()->id;
        $number = 1;
        foreach ($urls as $url) {
            $data['serial'] = $serial;
            $data['user_id'] = $userId;
            $data['path'] = $url;
            $data['name'] = 'url-' . $number;
            $number++;
            $data['ext'] = 'url';
            $data['size'] = 0;
            $data['hash'] = sha1($url);
            $res = M('attachment')->add($data);
        }
        if (empty($res)) {
            return false;
        }
        return $serial;
    }
}
